package com.company.ThreadDemo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 作者：13687
 * 日期：2017/6/4
 * 项目：ThreadPoolsDemo
 * 描述：从单纯的获取任务执行完后的结果
 * 到控制任务执行的过程
 * 1. 取消
 */
public class CallableDemo2 {
	public static void main(String[] args) throws Exception{
		ExecutorService es = Executors.newSingleThreadExecutor();
		Future<Number> future = es.submit(new CountCallable());
		System.out.println("任务开始于"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		future.cancel(true);
		if (future.isCancelled()) {
			System.out.println("任务被取消于"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			es.shutdownNow();
		}else{
			Number number = future.get();
			System.out.println("任务结束于"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			if(future.isDone()){
				System.out.println("任务执行完毕  result="+number.num);
				es.shutdown();
			}
		}
	}

	public static class CountCallable implements Callable<Number> {

		@Override
		public Number call() throws Exception {
			Number number = new Number();
			TimeUnit.SECONDS.sleep(5);
			number.setNum(10);
			return number;
		}

	}
	static class Number{
		private int num;
		private int getNum(){
			return num;
		}
		private void setNum(int num){
			this.num = num;
		}
	}
}
